package org.tagging.service.impl.other;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class EmailServiceImpl {
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    private static ConcurrentHashMap<String, String> codeMap = new ConcurrentHashMap<>();


    public String get(String key) {
        return codeMap.get(key);
    }


    public void remove(String key) {
        codeMap.remove(key);
    }

    public void sendCode(String username, String subject, String message) {
        String s = String.valueOf(System.currentTimeMillis());
//        String message = ;
        s = s.substring(s.length() - 6);
        this.send(username, subject, String.format(message, s));
        codeMap.put(username, s);
    }

    private void send(String to, String subject, String context) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(this.mailProperties.getUsername());
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(context);
        simpleMailMessage.setTo(to);
        this.javaMailSender.send(simpleMailMessage);
    }

    public boolean check(String username, String code) {
        if (codeMap.get(username)!=null&&codeMap.get(username).equals(code)) {
            codeMap.remove(username);
            return true;
        }
        return false;
    }
}

